/*!
 @name：infinite
 @date: 2022.07.13
 @update:yuguoliang
 @blog: http://www.web000.cn/
 */

;(function ($) {
    "use strict";

    var Infinite = function (el, distance) {
        this.container = $(el);
        this.container.data("infinite", this);
        this.distance = distance || 50;
        this.attachEvents();
    };

    //定义scroll方法
    Infinite.prototype.scroll = function () {
        var container = this.container;
        var scrollContainer = (container[0].tagName.toUpperCase() === "BODY" ? $(document) : container);
        var _scrollTop = scrollContainer.scrollTop();
        var _containerHeight = container.height();
        if (container[0].tagName.toUpperCase() === "BODY"){
            _scrollTop = document.body.scrollTop==0?document.documentElement.scrollTop:document.body.scrollTop;
            _containerHeight = $(window).height();
        }
        //判断滚动条距离底部多少距离
        var offset = container.scrollHeight() - (_containerHeight + _scrollTop);
        //达到最小距离则触发自定义事件infinite，执行相应加载ajax代码
        if (offset <= this.distance) {
            container.trigger("infinite");
        }
    };

    //定义attachEvents方法
    Infinite.prototype.attachEvents = function (off) {
        var el = this.container;
        var scrollContainer = (el[0].tagName.toUpperCase() === "BODY" ? $(document) : el);
        //绑定scroll事件,同等于scrollContainer.on('scroll',function(){})
        //scrollContainer['on']、scrollContainer['of']等同于scrollContainer.on、scrollContainer.off
        //$.proxy(this.scroll, this)给scrollContainer.on绑定事件代理this.scroll方法，使用当前上下文环境
        scrollContainer[off ? "off" : "on"]("scroll", $.proxy(this.scroll, this));
    };

    Infinite.prototype.detachEvents = function () {
        this.attachEvents(true);
    };

    $.fn.infinite = function (distance) {
        return this.each(function () {
            new Infinite(this, distance);
        });
    };

    $.fn.destroyInfinite = function () {
        return this.each(function () {
            var infinite = $(this).data("infinite");
            if (infinite && infinite.detachEvents) infinite.detachEvents();
        });
    };

    $.fn.scrollHeight = function () {
        return this[0].scrollHeight;
    };

})($);
